package com.cmcc.linlaker.ui.upload.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.cmcc.linlaker.R;
import com.cmcc.linlaker.application.LinhuApp;
import com.cmcc.linlaker.http.ApiDefine;
import com.cmcc.linlaker.ui.query.ProjectListActivity;
import com.cmcc.linlaker.ui.upload.CheckZxActivity;
import com.cmcc.linlaker.ui.upload.SelfDealActivity;
import com.cmcc.linlaker.ui.upload.UploadDetailActivity;
import com.cmcc.linlaker.ui.upload.UploadSelfDealDetailActivity;
import com.cmcc.linlaker.ui.upload.UploadZxActivity;
import com.cmcc.linlaker.ui.upload.adapter.UploadQuestionAdapter;
import com.cmcc.linlaker.ui.upload.bean.UploadQuestionBean;
import com.cmcc.linlaker.utils.IntentUtils;
import com.cmcc.linlaker.utils.SPHelper;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.utils.Utils;
import com.cmcc.linlaker.volley.GsonRequestHelper;
import com.zyyoona7.wheel.WheelView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ZxHistoryFragment extends Fragment {
    private View fragmentView;

    public static ZxHistoryFragment newInstance() {
        ZxHistoryFragment fragment = new ZxHistoryFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.fragment_zx_history, container, false);
        initView();
        return fragmentView;
    }

    private UploadQuestionAdapter adapter;
    private RecyclerView recycler_problem;
    private List<UploadQuestionBean.UploadQuestionData> itemList = new ArrayList<>();

    private MaterialRefreshLayout refreshLayout;

    private EditText edit_search, edit_problem_desc;
    private TextView text_jsfm;

    private void initView() {
        recycler_problem = fragmentView.findViewById(R.id.recycler_problem);
        setRecyclerView(recycler_problem, itemList);

        edit_search = fragmentView.findViewById(R.id.edit_search);
        edit_problem_desc = fragmentView.findViewById(R.id.edit_problem_desc);
        text_jsfm = fragmentView.findViewById(R.id.text_jsfm);
        edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //关闭软键盘
                    Utils.hideSoftKeyboard(getActivity(), edit_search);
                    String keyName = edit_search.getText().toString();

                    title = keyName;
                    reset(false);
                    return true;
                }
                return false;
            }
        });
        edit_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyName = edit_search.getText().toString();
                if (TextUtils.isEmpty(keyName)) {
                    title = "";
                    reset(false);
                }
            }
        });

        refreshLayout = fragmentView.findViewById(R.id.refresh);
        refreshLayout.setLoadMore(true);
        refreshLayout.setWaveShow(true);
        refreshLayout.setWaveColor(Color.parseColor("#f2f2f2"));

        refreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                reset(false);
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                if (isHasLoaded) {
                    ToastUtils.showText(getActivity(), "数据已全部加载");
                    refreshLayout.finishRefreshLoadMore();
                } else {
                    getProblemList(false, title, problemType);
                }
            }
        });

        fragmentView.findViewById(R.id.layout_high_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isShowSearch) {
                    fragmentView.findViewById(R.id.layout_search).setVisibility(View.GONE);
                } else {
                    fragmentView.findViewById(R.id.layout_search).setVisibility(View.VISIBLE);
                }
                isShowSearch = !isShowSearch;
            }
        });

        fragmentView.findViewById(R.id.view_hide).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isShowSearch) {
                    fragmentView.findViewById(R.id.layout_search).setVisibility(View.GONE);
                } else {
                    fragmentView.findViewById(R.id.layout_search).setVisibility(View.VISIBLE);
                }
                isShowSearch = !isShowSearch;

            }
        });
        fragmentView.findViewById(R.id.layout_top).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        fragmentView.findViewById(R.id.layout_jsfm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDict(fragmentView.findViewById(R.id.layout_problem), "jsfm");
            }
        });
        fragmentView.findViewById(R.id.text_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                problemType = "";
                title = "";
                edit_problem_desc.setText("");
                text_jsfm.setText("");
                edit_search.setText("");

                fragmentView.findViewById(R.id.layout_search).setVisibility(View.GONE);
                isShowSearch = false;

                reset(true);
            }
        });
        fragmentView.findViewById(R.id.text_search).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (jsfmPos != -1) {
                    problemType = LinhuApp.problemTypeList.get(jsfmPos).dictValue;
                }
                title = edit_problem_desc.getText().toString();

                fragmentView.findViewById(R.id.layout_search).setVisibility(View.GONE);
                isShowSearch = false;

                reset(true);
            }
        });

        getProblemList(true, title, problemType);
    }

    private boolean isShowSearch = false;

    private int pageSize = 20;
    private int pageNum = 1;
    private boolean isHasLoaded = false;

    private String title = "";
    private String problemType = "";

    private void reset(boolean isShowDialog) {
        itemList.clear();
        pageNum = 1;
        isHasLoaded = false;
        getProblemList(isShowDialog, title, problemType);
    }

    private void setRecyclerView(RecyclerView recycler_view, final List<UploadQuestionBean.UploadQuestionData> itemList) {
        recycler_view.setHasFixedSize(true);
        recycler_view.setLayoutManager(new LinearLayoutManager(getActivity()));

        recycler_view.setNestedScrollingEnabled(false);

        adapter = new UploadQuestionAdapter(getActivity(), itemList);
        adapter.setOnItemClickListener(new UploadQuestionAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {

                Intent intent = new Intent(getActivity(), UploadZxActivity.class);
                intent.putExtra("problemBean", itemList.get(position));
                startActivityForResult(intent, 100);

            }
        });
        recycler_view.setAdapter(adapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 100) {
            reset(false);
        }
    }

    /**
     * 获取列表
     */
    private void getProblemList(boolean isShowDialog, String title, String problemType) {
        GsonRequestHelper helper = new GsonRequestHelper(getActivity());
        Map<String, String> params = new HashMap<>();
        params.put("pageSize", pageSize + "");
        params.put("pageNum", pageNum + "");
        params.put("isAsc", "desc");
        params.put("problemSort", "3");
        params.put("userId", SPHelper.getUid());
        params.put("title", title);
        params.put("problemType", problemType);

        helper.sendPOSTRequest(ApiDefine.PROBLEM_LIST, UploadQuestionBean.class, params, isShowDialog, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    UploadQuestionBean bean = (UploadQuestionBean) data;
                    if (bean.code.equals("0")) {
                        List<UploadQuestionBean.UploadQuestionData> rows = bean.rows;

                        if (rows.size() == pageSize) {
                            itemList.addAll(bean.rows);
                            adapter.notifyDataSetChanged();
                            pageNum++;
                        } else {
                            itemList.addAll(bean.rows);
                            adapter.notifyDataSetChanged();
                            isHasLoaded = true;
                        }
                        refreshLayout.finishRefresh();
                        refreshLayout.finishRefreshLoadMore();

                        if (itemList.size() > 0) {
                            recycler_problem.setVisibility(View.VISIBLE);
                            fragmentView.findViewById(R.id.layout_no_data).setVisibility(View.GONE);
                        } else {
                            recycler_problem.setVisibility(View.GONE);
                            fragmentView.findViewById(R.id.layout_no_data).setVisibility(View.VISIBLE);
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(getActivity());
                    }
                }
            }
        });
    }

    private int jsfmPos = -1;

    private PopupWindow popupWindow;

    private void showDict(View view, final String tag) {
        if (popupWindow != null && popupWindow.isShowing()) {
            return;
        }
        RelativeLayout layout = (RelativeLayout) getLayoutInflater().inflate(R.layout.pop_dict, null);
        popupWindow = new PopupWindow(layout,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        // 产生背景变暗效果
        WindowManager.LayoutParams lp = getActivity().getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getActivity().getWindow().setAttributes(lp);


        //点击空白处时，隐藏掉pop窗口
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //添加弹出、弹入的动画
        popupWindow.setAnimationStyle(R.style.Popupwindow3);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        popupWindow.showAtLocation(view, Gravity.LEFT | Gravity.BOTTOM, 0, -location[1]);
        //添加按键事件监听
        setButtonListeners(layout, tag);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            // 在dismiss中恢复透明度
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getActivity().getWindow().setAttributes(lp);
            }
        });
    }

    private void setButtonListeners(RelativeLayout layout, final String tag) {
        TextView text_cancel = layout.findViewById(R.id.text_cancel);
        TextView text_ok = layout.findViewById(R.id.text_ok);
        final WheelView wheelview = layout.findViewById(R.id.wheelview);

        text_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });

        text_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

                if (tag.equals("jsfm")) {
                    jsfmPos = wheelview.getSelectedItemPosition();
                    text_jsfm.setText(LinhuApp.problemTypeList.get(jsfmPos).dictLabel);
                }
            }
        });

        //设置数据
        if (tag.equals("jsfm")) {
            wheelview.setData(LinhuApp.problemTypeList);
        }

        //尽请使用各种方法
        wheelview.setTextSize(20f, true);
        wheelview.setNormalItemTextColor(0xff666666);
        wheelview.setSelectedItemTextColor(0xff000000);
        wheelview.setDividerPaddingForWrap(13f);

        if (tag.equals("jsfm")) {
            wheelview.setSelectedItemPosition(jsfmPos);
        }
    }

}
